local extension = Package("rfenghou_song")
extension.extensionName = "aaa_fenghou"

local U = require "packages/utility/utility"

Fk:loadTranslationTable{
  ["rfenghou_song"] = "争宋",
  ["song"] = "宋",
}

local function AddWinAudio(general)
  local Win = fk.CreateActiveSkill{ name = general.name.."_win_audio" }
  Win.package = extension
  Fk:addSkill(Win)
end

Fk:appendKingdomMap("god", {"song"})

local yuefei = General:new(extension, "rfenghou__yuefei", "song", 4)
local zhengque = fk.CreateTriggerSkill{
  name = "rfenghou__zhengque",
  anim_type = "offensive",
  events = {fk.EventPhaseEnd},
  can_trigger = function(self, event, target, player, data)
    if target ~= player and player:hasSkill(self) and target.phase == Player.Play and
      player:usedSkillTimes(self.name, Player.HistoryRound) == 0 then
      local room = player.room
      if player:getMark(self.name) == 0 then
        local cards = U.getUniversalCards(room, "bt", false)
        cards = table.filter(cards, function (id)
          local card = Fk:getCardById(id)
          return card.is_damage_card and not card.multiple_targets
        end)
        room:setPlayerMark(player, self.name, cards)
      end
      return table.find(player:getMark(self.name), function (id)
        local card = Fk:getCardById(id)
        card.skillName = self.name
        return player:canUse(card, {bypass_distances = true, bypass_times = true})
      end)
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local use = U.askForUseRealCard(room, player, player:getMark(self.name), nil, self.name, "#rfenghou__zhengque-use",
      {expand_pile = player:getMark(self.name), bypass_distances = true, bypass_times = true}, true, true)
    if use then
      self.cost_data = use
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local use = {
      card = Fk:cloneCard(self.cost_data.card.name),
      from = player.id,
      tos = self.cost_data.tos,
      extraUse = true,
    }
    local to = room:getPlayerById(TargetGroup:getRealTargets(use.tos)[1])
    room:doIndicate(player.id, {to.id})
    local n = 0
    while true do
      if player.dead or player:isKongcheng() then break end
      local targets = room:getUseExtraTargets(use)
      if #targets == 0 then break end
      local cards = table.filter(player:getCardIds("h"), function (c)
        local card = Fk:getCardById(c)
        return card.type == Card.TypeBasic and card.trueName ~= "jink"
      end)
      local tos, id = room:askForChooseCardAndPlayers(player, targets, 1, 1, tostring(Exppattern{ id = cards }),
        "#rfenghou__zhengque-slash:::"..use.card.name, self.name, true, false)
      if #tos > 0 then
        n = n + 1
        TargetGroup:pushTargets(use.tos, tos[1])
        room:recastCard({id}, player, self.name)
      else
        break
      end
      if to.dead or to:isKongcheng() then break end
      cards = table.filter(to:getCardIds("h"), function (c)
        local card = Fk:getCardById(c)
        return card.type == Card.TypeBasic and card.trueName ~= "slash"
      end)
      tos, id = room:askForChooseCardAndPlayers(to, TargetGroup:getRealTargets(use.tos), 1, 1, tostring(Exppattern{ id = cards }),
        "#rfenghou__zhengque-jink:"..player.id.."::"..use.card.name, self.name, true, false)
      if #tos > 0 then
        n = n + 1
        TargetGroup:removeTarget(use.tos, tos[1])
        room:recastCard({id}, to, self.name)
      else
        break
      end
    end
    if n > 2 then
      player:setSkillUseHistory(self.name, 0, Player.HistoryRound)
    end
    if table.find(TargetGroup:getRealTargets(use.tos), function (id)
      local p = room:getPlayerById(id)
      return not p.dead and player:canUseTo(use.card, p, {bypass_distances = true, bypass_times = true})
    end) then
      room:useCard(use)
    end
  end
}
yuefei:addSkill(zhengque)
Fk:loadTranslationTable{
  ["rfenghou__yuefei"] = "岳飞",
  -- ["#rfenghou__yuefei"] = "",
  ["illustrator:rfenghou__yuefei"] = "伊达未来",
  ["designer:rfenghou__yuefei"] = "小须",

  ["rfenghou__zhengque"] = "铮阙",
  [":rfenghou__zhengque"] = "每轮限一次，其他角色出牌阶段结束时，你可以视为使用一张无距离限制的单目标伤害类牌，你与目标角色可以轮流执行："..
  "1.重铸一张不为【闪】的基本牌增加一个目标；2.重铸一张不为【杀】的基本牌取消一个目标。共执行三次后，你重置此技能。",
  ["#rfenghou__zhengque-use"] = "铮阙：是否视为使用一张伤害类牌？（无距离限制）",
  ["#rfenghou__zhengque-slash"] = "铮阙：是否重铸一张非【闪】基本牌，为此【%arg】增加一个目标？",
  ["#rfenghou__zhengque-jink"] = "铮阙：是否重铸一张非【杀】基本牌，取消 %src 使用【%arg】的一个目标？",
}


local hezhu = General:new(extension, "rfenghou__hezhu", "song", 4)
local gangrou = fk.CreateTriggerSkill{
  name = "rfenghou__gangrou",
  events = {fk.PreCardEffect},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and data.to and data.to ~= player.id and player:usedSkillTimes(self.name, Player.HistoryRound) == 0 and
      (data.card.trueName == "slash" or data.card.type == Card.TypeTrick) and
      #player.room:canMoveCardInBoard() > 0 and
      not (data.unoffsetable or data.disresponsive or
      table.contains(data.unoffsetableList or {}, data.to) or
      table.contains(data.disresponsiveList or {}, data.to))
  end,
  on_cost = function (self, event, target, player, data)
    local tos = player.room:askForChooseToMoveCardInBoard(player,
      "#rfenghou__gangrou-invoke::"..data.to..":"..data.card:toLogString(), self.name, true, nil, false)
    if #tos > 0 then
      self.cost_data = {tos = tos}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    for _, p in ipairs(room.alive_players) do
      room:setPlayerMark(p, "@!rfenghou__right", 0)
      room:setPlayerMark(p, "@!rfenghou__left", 0)
    end
    local target1 = room:getPlayerById(self.cost_data.tos[1])
    local target2 = room:getPlayerById(self.cost_data.tos[2])
    local result = room:askForMoveCardInBoard(player, target1, target2, self.name, nil)
    if result == nil then return end
    target1 = room:getPlayerById(result.from)
    target2 = room:getPlayerById(result.to)
    local side = ""
    if target1:distanceTo(target2, "left", false) > target1:distanceTo(target2, "right", false) then
      side = "left"
    elseif target1:distanceTo(target2, "left", false) < target1:distanceTo(target2, "right", false) then
      side = "right"
    end
    if side ~= "" then
      if not player.dead then
        if side == "left" then
          room:setPlayerMark(player, "@!rfenghou__right", 1)
        else
          room:setPlayerMark(player, "@!rfenghou__left", 1)
        end
      end
      for _, p in ipairs(room:getOtherPlayers(player)) do
        room:setPlayerMark(p, "@!rfenghou__"..side, 1)
      end
    end
    return true
  end,
}
local function distanceTo(from, other, mode)
  mode = mode or "both"
  if other == from then return 0 end
  if from:isRemoved() or other:isRemoved() then
    return -1
  end
  local right = 0
  local temp = from
  local try_time = 10
  for _ = 0, try_time do
    if temp == other then break end
    if not temp.dead and not temp:isRemoved() then
      right = right + 1
    end
    temp = temp.next
  end
  if temp ~= other then
    print("Distance malfunction: start and end does not match.")
  end
  local left = #Fk:currentRoom().alive_players - right - #table.filter(Fk:currentRoom().alive_players, function(p)
    return p:isRemoved()
  end)
  local ret = 0
  if mode == "left" then
    ret = left
  elseif mode == "right" then
    ret = right
  else
    ret = math.min(left, right)
  end

  local status_skills = Fk:currentRoom().status_skills[DistanceSkill] or Util.DummyTable
  for _, skill in ipairs(status_skills) do
    if skill.name ~= "#rfenghou__gangrou_distance" then
      local fixed = skill:getFixed(from, other)
      local correct = skill:getCorrect(from, other)
      if fixed ~= nil then
        ret = fixed
        break
      end
      ret = ret + (correct or 0)
    end
  end

  if from.fixedDistance[other] then
    ret = from.fixedDistance[other]
  end

  return math.max(ret, 1)
end
local gangrou_distance = fk.CreateDistanceSkill{
  name = "#rfenghou__gangrou_distance",
  fixed_func = function(self, from, to)
    if from:getMark("@!rfenghou__right") > 0 then
      return distanceTo(from, to, "right")
    elseif from:getMark("@!rfenghou__left") > 0 then
      return distanceTo(from, to, "left")
    end
  end,
}
gangrou:addRelatedSkill(gangrou_distance)
hezhu:addSkill(gangrou)
Fk:loadTranslationTable{
  ["rfenghou__hezhu"] = "贺铸",
  ["#rfenghou__hezhu"] = "侠意芳心",
  ["illustrator:rfenghou__hezhu"] = "白帝皇龙甲",
  ["designer:rfenghou__hezhu"] = "孤城",

  ["rfenghou__gangrou"] = "钢柔",
  ["#rfenghou__gangrou1"] = "请选择移出角色",
  ["#rfenghou__gangrou2"] = "请选择移入角色",
  ["@rfenghou__gangrouleft"] = "钢柔：顺时针",
  ["@rfenghou__gangrouright"] = "钢柔：逆时针",
  [":rfenghou__gangrou"] = "每轮限一次，当其他角色需要响应一张牌时，你可以移动场上一张牌，视为其响应之。若如此做，直到你下次发动此技能："..
  "你仅能从此牌移动的较短路径方向计算距离，其他角色仅能从此牌移动的较长路径方向计算距离。",
  ["#rfenghou__gangrou-invoke"] = "钢柔：%dest 需响应%arg，是否移动场上一张牌视为其响应之？",
  ["@rfenghou__gangrou"] = "",
}


local yangye = General:new(extension, "rfenghou__yangye", "song", 4)
local yanfeng = fk.CreateTriggerSkill{
  name = "rfenghou__yanfeng",
  anim_type = "offensive",
  events = {fk.AfterCardsMove},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and player.phase == Player.Play then
      local room = player.room
      local id = 0
      for _, move in ipairs(data) do
        if move.from == nil and move.moveReason == fk.ReasonUse then
          local move_event = room.logic:getCurrentEvent()
          local use_event = move_event.parent
          if use_event ~= nil and use_event.event == GameEvent.UseCard then
            local use = use_event.data[1]
            if use.from == player.id and use.card.trueName == "slash" and not use.card:isVirtual() and
              (player:usedSkillTimes(self.name, Player.HistoryPhase) == 0 or
              (use.extra_data and use.extra_data.rfenghou__yanfeng == player.id)) and
              table.contains(room.discard_pile, use.card.id) then
              for _, info in ipairs(move.moveInfo) do
                if info.cardId == use.card.id then
                  id = use.card.id
                end
              end
            end
          end
        end
      end
      if id == 0 then return end
      local cards = U.moveCardsHoldingAreaCheck(room, {id})
      if #cards > 0 then
        self.cost_data = cards
        return true
      end
    end
  end,
  on_cost = function (self, event, target, player, data)
    local use = U.askForUseRealCard(player.room, player, self.cost_data, nil, self.name,
      "#rfenghou__yanfeng-use:::"..Fk:getCardById(self.cost_data[1]):toLogString()..":"..
      (2 - player:usedSkillTimes(self.name, Player.HistoryPhase)),
      {
        expand_pile = self.cost_data,
        bypass_times = true,
        extraUse = true,
      },
      true, true)
    if use then
      self.cost_data = use
      return true
    elseif player:usedSkillTimes(self.name, Player.HistoryPhase) > 0 then
      player.room:setPlayerMark(player, "@rfenghou__yanfeng", 3)
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local use = self.cost_data
    if player:usedSkillTimes(self.name, Player.HistoryPhase) == 1 then
      room:setPlayerMark(player, "@rfenghou__yanfeng", 0)
      use.extra_data = use.extra_data or {}
      use.extra_data.rfenghou__yanfeng = player.id
    end
    room:useCard(use)
    if player.dead then return end
    if player:usedSkillTimes(self.name, Player.HistoryPhase) > 1 then
      room:setPlayerMark(player, "@rfenghou__yanfeng", 3)
    end
  end,
}
local yanfeng_delay = fk.CreateTriggerSkill{
  name = "#yanfeng_delay",
  events = {fk.DamageInflicted},
  mute = true,
  can_trigger = function(self, event, target, player, data)
    return target == player and player:getMark("@rfenghou__yanfeng") > 0
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    player:broadcastSkillInvoke("rfenghou__yanfeng")
    if player:getMark("@rfenghou__yanfeng") == 3 then
      room:notifySkillInvoked(player, "rfenghou__yanfeng", "negative")
      data.damage = 2
    elseif player:getMark("@rfenghou__yanfeng") == 2 then
      room:notifySkillInvoked(player, "rfenghou__yanfeng", "defensive")
      data.damage = 0
    elseif player:getMark("@rfenghou__yanfeng") == 1 then
      room:notifySkillInvoked(player, "rfenghou__yanfeng", "negative")
      data.damage = 3
    end
    room:removePlayerMark(player, "@rfenghou__yanfeng", 1)
  end,
}
yanfeng:addRelatedSkill(yanfeng_delay)
yangye:addSkill(yanfeng)
Fk:loadTranslationTable{
  ["rfenghou__yangye"] = "杨业",
  ["#rfenghou__yangye"] = "",
  ["illustrator:rfenghou__yangye"] = "梦想帝王",
  ["designer:rfenghou__yangye"] = "扬林",
  ["cv:rfenghou__yangye"] = "易大剧",

  ["rfenghou__yanfeng"] = "焱锋",
  [":rfenghou__yanfeng"] = "出牌阶段限一次，你可以将一张【杀】重复使用三次（在此【杀】进入弃牌堆后继续使用，仅第一次计入次数），然后直到"..
  "你下次发动此技能，你受到的前三次伤害依次改为2，0，3。",
  ["#rfenghou__yanfeng-use"] = "焱锋：你可以重复使用%arg三次！（还剩%arg2次）",
  ["@rfenghou__yanfeng"] = "焱锋",
  ["#yanfeng_delay"] = "焱锋",

  ["$rfenghou__yanfeng1"] = "破敌何殊逐雉兔？",
  ["$rfenghou__yanfeng2"] = "吞虏气填膺，报君忠贯日！",
  ["~rfenghou__yangye"] = "业非避死，盖时未有利……",
}

local zhangxiaoxiang = General:new(extension, "rfenghou__zhangxiaoxiang", "song", 3)

local suifen = fk.CreateTriggerSkill{
  name = "rfenghou__suifen",
  anim_type = "offensive",
  events = {fk.CardUsing},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and target == player and data.card:isCommonTrick() and data.tos
    and player:usedSkillTimes(self.name, Player.HistoryTurn) == 0
  end,
  on_cost = function (self, event, target, player, data)
    local tos = player.room:askForChoosePlayers(player, TargetGroup:getRealTargets(data.tos), 1, 1,
    "#rfenghou__suifen-choose:::"..data.card.name, self.name, true)
    if #tos > 0 then
      self.cost_data = {tos = tos}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = room:getPlayerById(self.cost_data.tos[1])
    local mark = player:getTableMark("@$rfenghou__suifen")
    if table.insertIfNeed(mark, data.card.name) then
      room:setPlayerMark(player, "@$rfenghou__suifen", mark)
    end
    room:damage { from = player, to = to, damage = 1, skillName = self.name, damageType = fk.FireDamage }
  end,

  on_lose = function (self, player, is_death)
    player.room:setPlayerMark(player, "@$rfenghou__suifen", 0)
  end,
}

local function hasSuffixMark(object, markname, suffixes)
  if not object then return false end
  for mark, _ in pairs(object.mark) do
    if mark == markname then return true end
    if mark:startsWith(markname .. "-") then
      for _, suffix in ipairs(suffixes) do
        if mark:find(suffix, 1, true) then return true end
      end
    end
  end
  return false
end

local suifen_prohibit = fk.CreateProhibitSkill{
  name = "#rfenghou__suifen_prohibit",
  is_prohibited = function (self, player, to, card)
    if player and to and table.contains(player:getTableMark("@$rfenghou__suifen"), card.name) then
      -- 警告：此处使用了未封装内容，非常危险
      local temp_suf = table.simpleClone(MarkEnum.TempMarkSuffix)
      local card_temp_suf = table.simpleClone(MarkEnum.CardTempMarkSuffix)
      local distanceCheck = player:distanceTo(to) > 1
      if distanceCheck then
        -- 监测不到extra_data的bypass_distances
        local status_skills = Fk:currentRoom().status_skills[TargetModSkill] or Util.DummyTable
        for _, skill in ipairs(status_skills) do
          if skill:bypassDistancesCheck(player, card.skill, card, to) then
            distanceCheck = false
            break
          end
        end
        if distanceCheck then
          distanceCheck = not
          (hasSuffixMark(card, MarkEnum.BypassDistancesLimit, card_temp_suf) or
          hasSuffixMark(player, MarkEnum.BypassDistancesLimit, temp_suf) or
          hasSuffixMark(to, MarkEnum.BypassDistancesLimitTo, temp_suf))
        end
      end
      if distanceCheck then return true end
      local timesCheck = player:usedCardTimes(card.name, Player.HistoryTurn) > 0
      if timesCheck then
        -- 监测不到extra_data的bypass_times
        local status_skills = Fk:currentRoom().status_skills[TargetModSkill] or Util.DummyTable
        for _, skill in ipairs(status_skills) do
          if skill:bypassTimesCheck(player, card.skill, Player.HistoryTurn, card, to) then
            timesCheck = false
            break
          end
        end
        if timesCheck then
          timesCheck = not
          (hasSuffixMark(card, MarkEnum.BypassTimesLimit, card_temp_suf) or
          hasSuffixMark(player, MarkEnum.BypassTimesLimit, temp_suf) or
          hasSuffixMark(to, MarkEnum.BypassTimesLimitTo, temp_suf))
        end
      end
      return timesCheck
    end
  end,
}
suifen:addRelatedSkill(suifen_prohibit)

zhangxiaoxiang:addSkill(suifen)

local xichen = fk.CreateTriggerSkill{
  name = "rfenghou__xichen",
  events = {fk.TurnEnd},
  frequency = Skill.Compulsory,
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and target == player and player:usedSkillTimes(self.name, Player.HistoryRound) == 0
      and not player:isKongcheng() then
      local room = player.room
      local cards = table.filter(player:getCardIds("h"), function (id)
        return not table.find(room.alive_players, function (p) return player:canUseTo(Fk:getCardById(id), p) end)
        -- 耦一个杀次数判断
        or table.contains(player:getTableMark("rfenghou__xichen_playphase-turn"), id)
      end)
      room:addPlayerMark(player, MarkEnum.BypassDistancesLimit)
      room:addPlayerMark(player, MarkEnum.BypassTimesLimit)
      -- 请勿使用extar_data参数
      cards = table.filter(cards, function (id) return player:canUse(Fk:getCardById(id)) end)
      room:removePlayerMark(player, MarkEnum.BypassDistancesLimit)
      room:removePlayerMark(player, MarkEnum.BypassTimesLimit)
      if #cards > 0 then
        self.cost_data = {cards = cards}
        return true
      end
    end
  end,
  on_cost = function (self, event, target, player, data)
    local cards = player.room:askForCard(player, 1, #self.cost_data.cards, false, self.name, true,
    tostring(Exppattern{ id = self.cost_data.cards }), "#rfenghou__xichen-cost")
    if #cards > 0 then
      self.cost_data.cards = cards
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    player:showCards(self.cost_data.cards)
    room:setPlayerMark(player, self.name, self.cost_data.cards)
    player:gainAnExtraTurn(true, self.name)
  end,

  refresh_events = {fk.BuryVictim, fk.TurnStart, fk.EventPhaseEnd, fk.EventPhaseStart},
  can_refresh = function (self, event, target, player, data)
    if event == fk.BuryVictim then
      return data.damage and data.damage.from == player and player:usedSkillTimes(self.name, Player.HistoryRound) > 0
      and player:hasSkill(self)
    elseif event == fk.TurnStart then
      if player:getCurrentExtraTurnReason() == self.name and player:getMark(self.name) ~= 0 then
        return true
      end
    else
      return target == player and player.phase == Player.Play
    end
  end,
  on_refresh = function (self, event, target, player, data)
    local room = player.room
    if event == fk.BuryVictim then
      player:setSkillUseHistory(self.name, 0, Player.HistoryRound)
    elseif event == fk.TurnStart then
      room:setPlayerMark(player, "rfenghou__xichen-turn", player:getMark(self.name))
      room:setPlayerMark(player, self.name, 0)
    elseif event == fk.EventPhaseEnd then
      -- 出牌阶段结束时，监测有没有次数用完的牌，让这些牌额外被“洗尘”回合结束时的效果监测到
      local temp_suf = table.simpleClone(MarkEnum.TempMarkSuffix)
      local card_temp_suf = table.simpleClone(MarkEnum.CardTempMarkSuffix)
      if hasSuffixMark(player, MarkEnum.BypassTimesLimit, temp_suf) then return end
      local status_skills = Fk:currentRoom().status_skills[TargetModSkill] or Util.DummyTable
      local timesCheck = function (card)
        for _, skill in ipairs(status_skills) do
          if skill:bypassTimesCheck(player, card.skill, Player.HistoryPhase, card, nil) then
            return true
          end
        end
        return false
      end
      local mark = {}
      for _, id in ipairs(player:getCardIds("h")) do
        local card = Fk:getCardById(id)
        local maxTimes = card.skill:getMaxUseTime(player, Player.HistoryPhase, card, nil) or 9999
        if player:usedCardTimes(card.trueName, Player.HistoryPhase) >= maxTimes
          and not hasSuffixMark(card, MarkEnum.BypassTimesLimit, card_temp_suf)
          and not timesCheck(card) then
          table.insert(mark, id)
        end
      end
      room:setPlayerMark(player, "rfenghou__xichen_playphase-turn", mark)
    elseif event == fk.EventPhaseStart then
      -- 额外出牌阶段清空记录……防一手潘濬
      room:setPlayerMark(player, "rfenghou__xichen_playphase-turn", 0)
    end
  end,
}

local xichen_prohibit = fk.CreateProhibitSkill{
  name = "#rfenghou__xichen_prohibit",
  prohibit_use = function (self, player, card)
    local mark = player:getMark("rfenghou__xichen-turn")
    if mark ~= 0 then
      local cards = Card:getIdList(card)
      return #cards == 0 or table.find(cards, function (id) return not table.contains(mark, id) end)
    end
  end,
}
suifen:addRelatedSkill(xichen_prohibit)

local xichen_targetmod = fk.CreateTargetModSkill{
  name = "#rfenghou__xichen_targetmod",
  bypass_times = function(self, player, skill, scope, card, to)
    return card and player:getMark("rfenghou__xichen-turn") ~= 0
  end,
  bypass_distances = function(self, player, skill, card, to)
    return player:getMark("rfenghou__xichen-turn") ~= 0
  end,
}
xichen:addRelatedSkill(xichen_targetmod)

zhangxiaoxiang:addSkill(xichen)
AddWinAudio(zhangxiaoxiang)
Fk:loadTranslationTable{
  ["rfenghou__zhangxiaoxiang"] = "张孝祥",
  ["#rfenghou__zhangxiaoxiang"] = "泪倾长淮",
  ["illustrator:rfenghou__zhangxiaoxiang"] = "啪啪三国",
  ["designer:rfenghou__zhangxiaoxiang"] = "拼音",
  ["cv:rfenghou__zhangxiaoxiang"] = "康了个猫",

  ["rfenghou__suifen"] = "燧愤",
  [":rfenghou__suifen"] = "每回合限一次，你使用普通锦囊牌时，可以对其中一名目标造成一点火焰伤害。此后你使用与之牌名相同的牌时，均具有为一的距离与次数限制。",
  ["@$rfenghou__suifen"] = "燧愤:限制牌",
  ["#rfenghou__suifen-choose"] = "燧愤：你可对一个目标造成1点火焰伤害，为【%arg】添加次数和距离限制",

  ["rfenghou__xichen"] = "洗尘",
  [":rfenghou__xichen"] = "每轮限一次，回合结束时，你可以展示任意张因次数或距离限制而无法使用的手牌，然后获得一个仅能使用这些牌且无次数和距离限制的回合。你杀死角色后，重置此技能。",
  ["#rfenghou__xichen-cost"] = "洗尘：可展示任意张因限制无法使用的手牌，获得一个仅能使用这些牌的额外回合",

  ["$rfenghou__suifen1"] = "孤光自照，肝肺皆冰雪。",
  ["$rfenghou__suifen2"] = "腰间剑、空埃蠹，竟何成？",
  ["$rfenghou__xichen1"] = "酌我清尊，洗公孤愤，来同一醉。",
  ["$rfenghou__xichen2"] = "时易失，心徒壮，岁将零。",
  ["~rfenghou__zhangxiaoxiang"] = "千古兴亡事、但陈悲迹。",
  ["$rfenghou__zhangxiaoxiang_win_audio"] = "三湘五管同民乐，万岁千秋与帝龄！",
}

local zhaoshu = General:new(extension, "rfenghou__zhaoshu", "song", 4)

local rfenghou__zhungu = fk.CreateTriggerSkill{
  name = "rfenghou__zhungu",
  events = {fk.AfterCardsMove, fk.Damaged},
  anim_type = "defensive",
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(self) then return false end
    if event == fk.AfterCardsMove then
      return data.extra_data and
      ((data.extra_data.rfenghou__zhunguLast and player:getMark("rfenghou__zhungu_last-round") == 0)
      or (data.extra_data.rfenghou__zhunguMax and player:getMark("rfenghou__zhungu_max-round") == 0))
    else
      return target == player and player:getMark("rfenghou__zhungu_damage-round") == 0
    end
  end,
  on_cost = function (self, event, target, player, data)
    local room = player.room
    local theEvent
    if event == fk.AfterCardsMove then
      if data.extra_data.rfenghou__zhunguLast then
        theEvent = "rfenghou__zhungu_last"
      elseif data.extra_data.rfenghou__zhunguMax then
        theEvent = "rfenghou__zhungu_max"
      end
    else
      theEvent = "rfenghou__zhungu_damage"
    end
    if not theEvent then return end
    local choices = {"draw1", "Cancel"}
    if player:isWounded() then
      table.insert(choices, 2, "recover")
    end
    local choice = room:askForChoice(player, choices, self.name, "#rfenghou__zhungu-choice")
    if choice ~= "Cancel" then
      room:setPlayerMark(player, theEvent.."-round", 1)
      self.cost_data = {choice = choice, event = theEvent}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local choice = self.cost_data.choice
    if choice == "draw1" then
      player:drawCards(1, self.name)
    else
      room:recover { num = 1, skillName = self.name, who = player, recoverBy = player }
    end
    if player.dead then return end
    local extra
    local list = {"rfenghou__zhungu_max", "rfenghou__zhungu_last", "rfenghou__zhungu_damage"}
    for _, name in ipairs(list) do
      if name ~= self.cost_data.event then
        local mark = player:getMark("@"..name)
        if mark ~= 0 then
          local hand, hp = table.unpack(table.map(mark, function(e) return tonumber(string.split(e, ":")[2]) end))
          if (choice == "draw1" and player:getHandcardNum() < hand) or (choice == "recover" and player.hp < hp) then
            extra = true
            break
          end
        end
      end
    end
    if extra then
      if choice == "draw1" then
        player:drawCards(1, self.name)
      else
        room:recover { num = 1, skillName = self.name, who = player, recoverBy = player }
      end
    end
  end,

  refresh_events = {fk.AfterCardsMove, fk.EventLoseSkill, fk.EventAcquireSkill, fk.GameStart, fk.Damaged},
  can_refresh = function (self, event, target, player, data)
    if event == fk.AfterCardsMove then
      if player:hasSkill(self, true) then
        for _, move in ipairs(data) do
          if move.toArea == Player.Hand then return true end
          for _, info in ipairs(move.moveInfo) do
            if info.fromArea == Player.Hand then
              return true
            end
          end
        end
      end
    elseif event == fk.GameStart then
      return player:hasSkill(self, true)
    elseif event == fk.Damaged then
      return player:hasSkill(self, true) and target == player
    else
      return data == self and target == player
    end
  end,
  on_refresh = function (self, event, target, player, data)
    local room = player.room
    local hand, hp = player:getHandcardNum(), player.hp
    local record = {"牌:"..hand, "体:"..hp}
    if event == fk.Damaged then
      room:setPlayerMark(player, "@rfenghou__zhungu_damage", record)
    elseif event == fk.EventLoseSkill then
      room:setPlayerMark(player, "@rfenghou__zhungu_damage", 0)
      room:setPlayerMark(player, "@rfenghou__zhungu_last", 0)
      room:setPlayerMark(player, "@rfenghou__zhungu_max", 0)
    else
      local oldKongcheng, oldMax = player.tag["rfenghou__zhungu_last"], player.tag["rfenghou__zhungu_max"]
      local newKongcheng, newMax = player:isKongcheng(), table.every(room.alive_players, function (p)
        return player:getHandcardNum() >= p:getHandcardNum()
      end)
      player.tag["rfenghou__zhungu_last"] = newKongcheng
      player.tag["rfenghou__zhungu_max"] = newMax
      if event == fk.AfterCardsMove then
        if newKongcheng and oldKongcheng == false then
          data.extra_data = data.extra_data or {}
          data.extra_data.rfenghou__zhunguLast = true
          room:setPlayerMark(player, "@rfenghou__zhungu_last", record)
        end
        if newMax and oldMax == false then
          data.extra_data = data.extra_data or {}
          data.extra_data.rfenghou__zhunguMax = true
          room:setPlayerMark(player, "@rfenghou__zhungu_max", record)
        end
      end
    end
  end,
}
zhaoshu:addSkill(rfenghou__zhungu)

local rfenghou__zhunshi = fk.CreateTriggerSkill{
  name = "rfenghou__zhunshi",
  events = {fk.AfterCardsMove, fk.HpRecover, fk.TurnEnd},
  anim_type = "defensive",
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(self) then return false end
    if event == fk.AfterCardsMove then
      local current = player.room.current
      if current and current ~= player and not current.dead then
        for _, move in ipairs(data) do
          if move.to == player.id and move.toArea == Player.Hand and move.moveReason == fk.ReasonDraw then
            return true
          end
        end
      end
    elseif event == fk.HpRecover then
      if target == player then
        local current = player.room.current
        return current and current ~= player and not current.dead and current:isWounded()
      end
    else
      return player:getMark("@@rfenghou__zhunshi-turn") ~= 0
    end
  end,
  on_cost = function (self, event, target, player, data)
    local room = player.room
    if event == fk.TurnEnd then
      self.cost_data = nil
      return true
    end
    local current = room.current
    self.cost_data = {tos = {current.id}}
    return room:askForSkillInvoke(player, self.name, nil, (event == fk.AfterCardsMove 
    and "#rfenghou__zhunshi-draw::"..current.id or "#rfenghou__zhunshi-recover::"..current.id..":"..data.num))
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if event == fk.TurnEnd then
      player:gainAnExtraTurn(true, self.name)
    else
      local current = room.current
      if event == fk.AfterCardsMove then
        current:drawCards(1, self.name)
        room:setPlayerMark(player, "rfenghou__zhunshi1-turn", 1)
      else
        room:recover { num = data.num, skillName = self.name, who = current, recoverBy = player }
        room:setPlayerMark(player, "rfenghou__zhunshi2-turn", 1)
      end
      if player:getMark("rfenghou__zhunshi1-turn") == 1 and player:getMark("rfenghou__zhunshi2-turn") == 1 then
        room:setPlayerMark(player, "@@rfenghou__zhunshi-turn", 1)
      end
    end
  end,
}
zhaoshu:addSkill(rfenghou__zhunshi)

local rfenghou__zhundeng = fk.CreateTriggerSkill{
  name = "rfenghou__zhundeng$",
  events = {fk.HpRecover},
  anim_type = "defensive",
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and target ~= player and (target.kingdom == "song" or not player:isNude())
  end,
  on_cost = function (self, event, target, player, data)
    self.cost_data = {tos = {player.id}}
    return player.room:askForSkillInvoke(target, self.name, nil,
    "#rfenghou__zhundeng-"..(target.kingdom == "song" and "draw:" or "recast:")..player.id)
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if target.kingdom == "song" then
      player:drawCards(1, self.name)
    else
      local cards = room:askForCard(player, 1, 1, true, self.name, false, ".", "#rfenghou__zhundeng-card")
      room:recastCard(cards, player, self.name)
    end
  end,
}
zhaoshu:addSkill(rfenghou__zhundeng)
AddWinAudio(zhaoshu)
Fk:loadTranslationTable{
  ["rfenghou__zhaoshu"] = "赵曙",
  ["#rfenghou__zhaoshu"] = "玉营守晨",
  ["illustrator:rfenghou__zhaoshu"] = "梦想帝王",
  ["designer:rfenghou__zhaoshu"] = "廷玉",
  ["cv:rfenghou__zhaoshu"] = "超绝天",

  ["rfenghou__zhungu"] = "谆古",
  [":rfenghou__zhungu"] = "每轮各限一次，当你受到伤害后，失去最后手牌后，手牌数成为全场最大后，你可以选择回复1点体力或摸一张牌，然后若体力值/手牌数小于你上次触发的任一另外时机的此值，再执行一次。",
  ["@rfenghou__zhungu_damage"] = "谆伤",
  ["@rfenghou__zhungu_last"] = "谆失",
  ["@rfenghou__zhungu_max"] = "谆大",
  ["#rfenghou__zhungu-hp"] = "调整体力值至 %arg",
  ["#rfenghou__zhungu-hand"] = "调整手牌数至 %arg",
  ["#rfenghou__zhungu-choice"] = "谆古：你可以选择回复1点体力或摸一张牌",

  ["rfenghou__zhunshi"] = "谆士",
  [":rfenghou__zhunshi"] = "你于回合外摸牌后，可以令当前回合角色摸一张牌；你于回合外回复体力后，可以令当前回合角色回复等量体力。你均如此做过的回合结束后，你执行一个额外回合。",
  ["@@rfenghou__zhunshi-turn"] = "谆士:额外回合",
  ["#rfenghou__zhunshi-recover"] = "谆士：你可以令 %dest 回复 %arg 点体力",
  ["#rfenghou__zhunshi-draw"] = "谆士：你可以令 %dest 摸一张牌",

  ["rfenghou__zhundeng"] = "谆登",
  [":rfenghou__zhundeng"] = "主公技，其他角色回复体力后，其可以令你重铸一张牌，若为宋势力角色，改为摸一张牌。",
  ["#rfenghou__zhundeng-recast"] = "谆登：你可以令 %src 重铸一张牌",
  ["#rfenghou__zhundeng-draw"] = "谆登：你可以令 %src 摸一张牌",
  ["#rfenghou__zhundeng-card"] = "谆登：请重铸一张牌",

  ["$rfenghou__zhungu1"] = "庶有疑嫡之子，朝有疑相之臣，国家乱矣。",
  ["$rfenghou__zhungu2"] = "父没，三年无改父之道，圣人教也。",
  ["$rfenghou__zhunshi1"] = "诲尔谆谆，听我藐藐；驰慢不一，难堪大任。",
  ["$rfenghou__zhunshi2"] = "乱父子纲常，坏圣人之道，讵不谆哉？",
  ["$rfenghou__zhundeng1"] = "天视自我民视，天听自我民听。",
  ["$rfenghou__zhundeng2"] = "之中国、践大宝；天与之，人与之！",
  ["~rfenghou__zhaoshu"] = "数年空期盼、一夕沾濡，犹自洗不净。",
  ["$rfenghou__zhaoshu_win_audio"] = "皇皇万国宾，日出日入土，普为大宋臣。",
}

local luyou = General:new(extension, "rfenghou__luyou", "song", 3)
local wangshi = fk.CreateTriggerSkill{
  name = "rfenghou__wangshi",
  anim_type = "drawcard",
  frequency = Skill.Compulsory,
  events = {fk.AfterCardsMove},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) then
      local cards = {}
      for _, move in ipairs(data) do
        if move.toArea == Card.DiscardPile and move.skillName ~= self.name then
          if move.from == player.id then
            for _, info in ipairs(move.moveInfo) do
              if Fk:getCardById(info.cardId).trueName == "slash" and info.fromArea == Card.PlayerHand then
                table.insertIfNeed(cards, info.cardId)
              end
            end
          elseif move.from == nil and
            table.contains({fk.ReasonUse, fk.ReasonResonpse, fk.ReasonPutIntoDiscardPile}, move.moveReason) then
            local parent_event = player.room.logic:getCurrentEvent().parent
            if parent_event ~= nil then
              local card_ids = {}
              if parent_event.event == GameEvent.UseCard or parent_event.event == GameEvent.RespondCard then
                local use = parent_event.data[1]
                if use.from == player.id and not use.damageDealt then
                  parent_event:searchEvents(GameEvent.MoveCards, 1, function(e2)
                    if e2.parent and e2.parent.id == parent_event.id then
                      for _, move2 in ipairs(e2.data) do
                        if (move2.moveReason == fk.ReasonUse or move2.moveReason == fk.ReasonResonpse) then
                          for _, info in ipairs(move2.moveInfo) do
                            if Fk:getCardById(info.cardId).trueName == "slash" and info.fromArea == Card.PlayerHand then
                              table.insertIfNeed(card_ids, info.cardId)
                            end
                          end
                        end
                      end
                    end
                  end)
                end
              elseif parent_event.event == GameEvent.Pindian then
                local pindian = parent_event.data[1]
                if pindian.from == player then
                  card_ids = player.room:getSubcardsByRule(pindian.fromCard)
                elseif pindian.results[player.id] then
                  card_ids = player.room:getSubcardsByRule(pindian.results[player.id].toCard)
                end
              end
              if #card_ids > 0 then
                for _, info in ipairs(move.moveInfo) do
                  if Fk:getCardById(info.cardId).trueName == "slash" and table.contains(card_ids, info.cardId) and
                    info.fromArea == Card.Processing then
                    table.insertIfNeed(cards, info.cardId)
                  end
                end
              end
            end
          end
        end
      end
      cards = table.filter(cards, function (id)
        return table.contains(player.room.discard_pile, id)
      end)
      cards = U.moveCardsHoldingAreaCheck(player.room, cards)
      if #cards > 0 then
        self.cost_data = cards
        return true
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:moveCardTo(self.cost_data, Card.PlayerHand, player, fk.ReasonJustMove, self.name, nil, true, player.id)
    if player.dead then return end
    player:drawCards(1, self.name)
    if player.dead then return end
    local n = player:usedSkillTimes(self.name, Player.HistoryTurn)
    room:askForDiscard(player, n, n, true, self.name, false)
    if player.dead then return end
    local phase_event = room.logic:getCurrentEvent():findParent(GameEvent.Phase)
    if phase_event == nil or phase_event.data[1] ~= player then return end
    player._phase_end = true
    player:gainAnExtraPhase(phase_event.data[2], true)
  end,
}
local xianggu = fk.CreateViewAsSkill{
  name = "rfenghou__xianggu",
  pattern = ".",
  frequency = Skill.Compulsory,  --锁定转化技！
  prompt = function (self)
    local card = Fk:cloneCard(Self:getMark("rfenghou__xianggu"))
    if card.sub_type == Card.SubtypeWeapon then
      return "#rfenghou__xianggu1"
    else
      return "#rfenghou__xianggu2"
    end
  end,
  interaction = function(self)
    local all_names = {}
    if Self:getMark("rfenghou__xianggu") ~= 0 then
      local card = Fk:cloneCard(Self:getMark("rfenghou__xianggu"))
      if card.sub_type == Card.SubtypeWeapon then
        all_names = Self:getTableMark("rfenghou__xianggu-turn")
      else
        all_names = {"slash"}
      end
    end
    local names = U.getViewAsCardNames(Self, self.name, all_names)
    if #names > 0 then
      return U.CardNameBox {choices = names, all_choices = all_names}
    end
  end,
  card_filter = function (self, to_select, selected)
    if #selected == 0 then
      local card = Fk:cloneCard(Self:getMark("rfenghou__xianggu"))
      if card.sub_type == Card.SubtypeWeapon then
        return Fk:getCardById(to_select).trueName == "slash"
      else
        return table.contains(Self:getTableMark("rfenghou__xianggu-turn"), Fk:getCardById(to_select).name)
      end
    end
  end,
  view_as = function(self, cards)
    if #cards ~= 1 or self.interaction.data == nil then return end
    local card = Fk:cloneCard(self.interaction.data)
    card.skillName = self.name
    card:addSubcard(cards[1])
    return card
  end,
  enabled_at_play = function (self, player)
    return player:getMark("rfenghou__xianggu") ~= 0 and #player:getTableMark("rfenghou__xianggu-turn") > 0
  end,
  enabled_at_response = function (self, player, response)
    return player:getMark("rfenghou__xianggu") ~= 0 and #player:getTableMark("rfenghou__xianggu-turn") > 0 and not response
  end,
}
local xianggu_trigger = fk.CreateTriggerSkill{
  name = "#rfenghou__xianggu_trigger",
  frequency = Skill.Compulsory,

  refresh_events = {fk.AfterCardsMove, fk.EventAcquireSkill, fk.EventLoseSkill,
    fk.StartPlayCard, fk.AskForCardUse},
  can_refresh = function(self, event, target, player, data)
    if event == fk.AfterCardsMove then
      if player:hasSkill(self, true) then
        for _, move in ipairs(data) do
          if move.toArea == Card.DiscardPile then
            for _, info in ipairs(move.moveInfo) do
              if Fk:getCardById(info.cardId).type == Card.TypeEquip then
                return true
              end
            end
          end
        end
      end
    elseif event == fk.EventAcquireSkill or event == fk.EventLoseSkill then
      return target == player and data == xianggu
    elseif event == fk.StartPlayCard or event == fk.AskForCardUse then
      return target == player and player:hasSkill(xianggu)
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if event == fk.AfterCardsMove then
      if player:getMark("rfenghou__xianggu") ~= 0 then
        local card = Fk:cloneCard(player:getMark("rfenghou__xianggu"))
        if not table.find(player:getEquipments(card.sub_type), function (id)
          return Fk:getCardById(id).name == player:getMark("rfenghou__xianggu")
        end) then
          local skill = card.equip_skill
          room:handleAddLoseSkills(player, "-"..skill.name, nil, false, false)
        end
        room:setPlayerMark(player, "rfenghou__xianggu", 0)
        room:setPlayerMark(player, "@rfenghou__xianggu", 0)
      end
      local name = ""
      for i = #data, 1, -1 do
        local move = data[i]
        if move.toArea == Card.DiscardPile then
          for j = #move.moveInfo, 1, -1 do
            local info = move.moveInfo[j]
            if Fk:getCardById(info.cardId).type == Card.TypeEquip then
              name = Fk:getCardById(info.cardId).name
            end
          end
        end
      end
      if name ~= "" then
        local card = Fk:cloneCard(name)
        room:handleAddLoseSkills(player, card.equip_skill.name, nil, false, false)
        room:setPlayerMark(player, "rfenghou__xianggu", name)
        room:setPlayerMark(player, "@rfenghou__xianggu", Fk:translate(name))
      end
    elseif event == fk.EventAcquireSkill then
      local name = ""
      room.logic:getEventsByRule(GameEvent.MoveCards, 1, function (e)
        for i = #e.data, 1, -1 do
          local move = e.data[i]
          if move.toArea == Card.DiscardPile then
            for j = #move.moveInfo, 1, -1 do
              local info = move.moveInfo[j]
              if Fk:getCardById(info.cardId).type == Card.TypeEquip then
                name = Fk:getCardById(info.cardId).name
              end
            end
          end
        end
      end, 1)
      if name ~= "" then
        local card = Fk:cloneCard(name)
        room:handleAddLoseSkills(player, card.equip_skill.name, nil, false, false)
        room:setPlayerMark(player, "rfenghou__xianggu", name)
        room:setPlayerMark(player, "@rfenghou__xianggu", Fk:translate(name))
      end
    elseif event == fk.EventLoseSkill then
      if player:getMark("rfenghou__xianggu") ~= 0 then
        local card = Fk:cloneCard(player:getMark("rfenghou__xianggu"))
        if not table.find(player:getEquipments(card.sub_type), function (id)
          return Fk:getCardById(id).name == player:getMark("rfenghou__xianggu")
        end) then
          local skill = card.equip_skill
          room:handleAddLoseSkills(player, "-"..skill.name, nil, false, false)
        end
        room:setPlayerMark(player, "rfenghou__xianggu", 0)
        room:setPlayerMark(player, "@rfenghou__xianggu", 0)
      end
    elseif event == fk.StartPlayCard or event == fk.AskForCardUse then
      local cards = {}
      room.logic:getEventsOfScope(GameEvent.UseCard, 1, function(e)
        local use = e.data[1]
        if use.responseToEvent and use.responseToEvent.card then
          table.insertIfNeed(cards, use.responseToEvent.card.name)
        end
      end, Player.HistoryTurn)
      room:setPlayerMark(player, "rfenghou__xianggu-turn", cards)
    end
  end,
}
local xianggu_attackrange = fk.CreateAttackRangeSkill{
  name = "#rfenghou__xianggu_attackrange",
  correct_func = function (self, from, to)
    if from:getMark("rfenghou__xianggu") ~= 0 and from:hasSkill(xianggu) then
      local card = Fk:cloneCard(from:getMark("rfenghou__xianggu"))
      if card.sub_type == Card.SubtypeWeapon then
        local n = card.attack_range
        local nums = {}
        if #from:getEquipments(Card.SubtypeWeapon) > 0 then
          for _, id in ipairs(from:getEquipments(Card.SubtypeWeapon)) do
            table.insert(nums, Fk:getCardById(id).attack_range)
          end
        end
        if #nums > 0 then
          local orig = math.max(table.unpack(nums))
          if n > orig then
            return n - orig
          else
            return 0
          end
        else
          return n
        end
      end
    end
    return 0
  end,
}
xianggu:addRelatedSkill(xianggu_trigger)
xianggu:addRelatedSkill(xianggu_attackrange)
luyou:addSkill(wangshi)
luyou:addSkill(xianggu)
Fk:loadTranslationTable{
  ["rfenghou__luyou"] = "陆游",
  ["#rfenghou__luyou"] = "金戈入梦",
  ["illustrator:rfenghou__luyou"] = "英雄杀",
  ["designer:rfenghou__luyou"] = "拼音",

  ["rfenghou__wangshi"] = "望师",
  [":rfenghou__wangshi"] = "锁定技，当你不以此法失去的【杀】进入弃牌堆后，若此牌未造成伤害，你收回之，摸一张牌并弃置X张牌；"..
  "若此时是你的回合内，你重新开始当前阶段（X为本回合此技能发动次数）。",
  ["rfenghou__xianggu"] = "香故",
  [":rfenghou__xianggu"] = "锁定技，你视为装备着上一张进入弃牌堆的装备牌。若为武器牌，你可以将一张【杀】当此回合被抵消过的一张牌使用；"..
  "若不为武器牌，你可以将一张此回合被抵消过的牌当【杀】使用。",
  ["#rfenghou__xianggu1"] = "香故：你可以将一张【杀】当此回合被抵消过的一张牌使用",
  ["#rfenghou__xianggu2"] = "香故：你可以将一张此回合被抵消过的牌当【杀】使用",
  ["@rfenghou__xianggu"] = "香故",
}

return extension
